import React from "react";

import "./App.css";

let curTab = "Tab1";

class Tabs extends React.Component {
  state = {
    curTab: "Tab1",
  };

  change(str: string) {
    // 修改外部数据,不会引起组件的重新 Render
    // curTab = str;
    // console.log("curTab", curTab);
    // 只有 State 与 Props 的变化,才会引起组件重新 Render
    // this.setState({ curTab: str });
    // Props 数据是只读的,不能修改
    // this.props.curTab = str;

    // 调用父组件传递过来的函数
    this.props.onChange(str);
  }

  render() {
    console.log("Render");
    const { curTab } = this.props;
    return (
      <div>
        <button
          className={`button ${curTab === "Tab1" ? "active" : ""}`}
          onClick={() => this.change("Tab1")}
        >
          Tab1
        </button>
        <button
          className={`button ${curTab === "Tab2" ? "active" : ""}`}
          onClick={() => this.change("Tab2")}
        >
          Tab2
        </button>
        <button
          className={`button ${curTab === "Tab3" ? "active" : ""}`}
          onClick={() => this.change("Tab3")}
        >
          Tab3
        </button>
      </div>
    );
  }
}

class App extends React.Component {
  state = {
    curTab: "Tab1",
  };

  render() {
    return (
      <div>
        <h1>App</h1>

        <Tabs
          curTab={this.state.curTab}
          onChange={(str) => {
            console.log("传递给 Tabs 的 onChange");

            // 修改自己的 state 数据
            this.setState({ curTab: str });
          }}
        />
      </div>
    );
  }
}

export default App;
